package system

import (
	"github.com/gin-gonic/gin"
	"server/global"
	comRequest "server/model/common/request"
	"server/model/common/response"
	sysModel "server/model/system"
	sysRequest "server/model/system/request"
	sysService "server/service/system"
)

type PermissionApi struct {
}

// 首页接口
func (perm *PermissionApi) Index(c *gin.Context) {
	p := &sysRequest.SysPermissionGetList{}
	if err := c.ShouldBind(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//权限列表
	permList, err := sysService.PermissionServiceApp.GetPermList(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	var permTreeList []*sysModel.SysPermission
	if p.Name == "" && p.DisplayName == "" {
		permTreeList = sysService.PermissionServiceApp.BuildTree(permList)
	} else {
		permTreeList = permList
	}
	response.OkWithData(gin.H{
		"permList": permTreeList,
	}, c)
}

//保存权限数据
func (perm *PermissionApi) Save(c *gin.Context) {
	p := &sysModel.SysPermission{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	rows, err := sysService.PermissionServiceApp.SavePerm(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(gin.H{
		"rows": rows,
	}, c)
}

//菜单删除
func (perm *PermissionApi) Destroy(c *gin.Context) {
	p := &comRequest.IdsReq{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	rows, err := sysService.PermissionServiceApp.DelPerm(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(gin.H{
		"rows": rows,
	}, c)
}

// 设置排序
func (perm *PermissionApi) SetOrder(c *gin.Context) {
	p := &sysRequest.SysPermissionSetOrder{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	err := sysService.PermissionServiceApp.SetOrder(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(gin.H{
		"p": p,
	}, c)
}
